package org.example.nettydemo.netty.mqtt;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageDecoder;

import java.util.List;

/**
 * MQTT协议解码器
 */
public class MqttDecoder extends ByteToMessageDecoder {
    @Override
    protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) {
        if (in.readableBytes() < 2) { // 至少有2字节才能解析
            return;
        }

        in.markReaderIndex(); // 标记当前读索引

        byte firstByte = in.readByte();
        int remainingLength = decodeRemainingLength(in); // 解析剩余长度
        if (in.readableBytes() < remainingLength) {
            in.resetReaderIndex();
            return; // 数据不完整，等待更多数据
        }

        ByteBuf mqttPayload = in.readBytes(remainingLength); // 读取完整数据
        out.add(new MqttMessage(firstByte, mqttPayload)); // 解析为 MQTT 消息对象
    }

    private int decodeRemainingLength(ByteBuf in) {
        int value = 0, multiplier = 1;
        byte encodedByte;
        do {
            if (!in.isReadable()) {
                return -1;
            }
            encodedByte = in.readByte();
            value += (encodedByte & 127) * multiplier;
            multiplier *= 128;
        } while ((encodedByte & 128) != 0);
        return value;
    }
}

/**
 * MQTT 消息对象
 */
class MqttMessage {
    private final byte type;
    private final ByteBuf payload;

    public MqttMessage(byte type, ByteBuf payload) {
        this.type = type;
        this.payload = payload;
    }

    public byte getType() {
        return type;
    }

    public ByteBuf getPayload() {
        return payload;
    }

    @Override
    public String toString() {
        return "MQTT Message Type: " + (type >> 4);
    }
}
